/* Copyright Andy Mitchell 2007. No warranties */

function FilterPopupUI(gtdinboxPage, name, type, elParentPopuper, parentNames, parentTypes, parentSearch, filterParent){
try{
	this._gtdinboxPage = gtdinboxPage;
	this._doc = gtdinboxPage.doc;
	this._sp = gtdinboxPage.sp;
	this._labels = gtdinboxPage._labels;
	this._parentNames = parentNames || [];
	this._parentTypes = parentTypes || [type];
	this._parentSearch = parentSearch || "";
	if( name instanceof Array ){	// contact, [name,email]
		this._name = name[0];
		this._email = name[1];
		if( !this._email ){
			this._email = this._sp.getEmailForContactName(this._name);
		}
	}else{
		this._name = name;
	}
	this._type = type;
	this._elParentPopuper = elParentPopuper;
	this._filterParent = filterParent;
	if( filterParent ){
		this._filterParent.highlighted(false);
	}
	
	this._eventObservers = new EventObservers(this);
	this._showHiders = [];
	
	this._create();
	this._eventObservers.observe( this.el, "click", this.mouseDown, true);
	this._eventObservers.observe( this.el, "contextmenu", this.contextMenu, true);
	
	this.highlighted(true);
	this.addPopupChildObject( this );
	
	return this;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI construct\n" + e.toString());
}
};

FilterPopupUI.prototype._create = function(){
try{
	this.el = this._doc.createElement("DIV");
		this.el.className = "filter-popup";
	var doc = this._gtdinboxPage.gmailDOM.element("document");
	if( doc ) doc.body.appendChild( this.el );
	
	var elTitle = this._doc.createElement("DIV");
		elTitle.className = "title";
		if( this._parentNames.length > 0 ){
			elTitle.innerHTML = "<div class='path'>" + this._parentNames.join(", ") + "</div>";
		}
		elTitle.innerHTML += (this._name || this._email || "");
	this.el.appendChild( elTitle );
	var elClose = this._doc.createElement("IMG");
		elClose.src = "chrome://gtdinbox/content/cross.png";
		elClose.className = "close-button";
		elClose.style.position = "absolute";
		elClose.style.right = "0px";
		elClose.style.top = "0px";
		this._eventObservers.observe(elClose, "mousedown", this.clickClose, false);
	elTitle.appendChild(elClose);
	
	this._popuper = new Popuper(this._gtdinboxPage, this.el, this);
	this._popuper.addEventHandler( this, "popupOff", this.onPopupOff );	
	
	this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.ShowAll"), "");
	
	switch( this._type ){
		case "Statuses":
			// Show Personal
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.Personal"), GIPROTOTYPE.restrictSearchToUser(this._gtdinboxPage._environment.emails) );	
			
			// Review
			var d = (new Date()).valueOf();
			var day = 1000*60*60*24;
			var elReviews = this._doc.createElement("DIV");
			
			this._createLink( elReviews, this._gtdinboxPage.stringBundle.getString("FilterPopup.Reviews.Recent"), "after:" + GIPROTOTYPE.searchDate(d-(day*7)) );	
			this._createLink( elReviews, this._gtdinboxPage.stringBundle.getString("FilterPopup.Reviews.OneWeekOld"), "before:" + GIPROTOTYPE.searchDate(d-(day*7)) );		
			this._createLink( elReviews, this._gtdinboxPage.stringBundle.getString("FilterPopup.Reviews.OneMonthOld"), "before:" + GIPROTOTYPE.searchDate(d-(day*31)) );	
			this._createLink( elReviews, this._gtdinboxPage.stringBundle.getString("FilterPopup.Reviews.ThreeMonthsOld"), "before:" + GIPROTOTYPE.searchDate(d-(day*66)) );
			
			this._createBreak();
			this._createSection(this._gtdinboxPage.stringBundle.getString("FilterPopup.Review"), elReviews);	
			
			break;
		case "Projects":
			var statusLabels = this._labels.getLabelsArray("Statuses");	// TODO ShowAllTasks appears in Dashboard too, tidy up?
			var statusStr = "(";
			var statusFinished = this._gtdinboxPage.settings.labels.types.Statuses.prefix + this._gtdinboxPage.settings.labels.types.Statuses.defaults.Finished;
			for( var i = 0; i < statusLabels.length; i++ ) if(statusLabels[i]!=statusFinished) statusStr += ((i>0)? " OR ":"") + GIPROTOTYPE.searchableLabel(statusLabels[i]);
			statusStr += ")";
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.ShowAllTasks"), statusStr);
			this._createStatuses();
			if(!this._hasParentType("Contexts")) this._createLabelsSection("Contexts");	
			if(!this._hasParentType("Contexts")) this._createLabelsSection("References");
			this._createContactsSectionByLabel();
			this._createBreak();
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.AssociatedFiles"), "has:attachment");	
			
			// Create rename
			var newLabel = this._gtdinboxPage.settings.labels.types.Old.prefix + this._name;
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.RenameAs") + " " + newLabel, "special.rename:" + this._name + "|,|" + newLabel, null, null, false, true, true);
			
			break;
		case "Contexts":
			this._createStatuses();
			if(!this._hasParentType("Contexts")) this._createLabelsSection("Projects");
			if(!this._hasParentType("Contexts")) this._createLabelsSection("References");
			this._createContactsSectionByLabel();
			this._createBreak();
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.AssociatedFiles"), "has:attachment");	
			break;
		case "References":
			// Show Personal
			this._createLink(this.el, "Sent To Self", GIPROTOTYPE.restrictSearchToUser(this._gtdinboxPage._environment.emails) );	
			if(!this._hasParentType("Contexts")) this._createLabelsSection("Contexts");
			if(!this._hasParentType("Contexts")) this._createLabelsSection("Projects");
			this._createBreak();
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.AssociatedFiles"), "has:attachment");	
			break;
		case "Misc":
			this._createStatuses();
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.AssociatedFiles"), "has:attachment");	
			break;
		case "Old":
			var newLabel = this._name.replace(this._gtdinboxPage.settings.labels.types.Old.prefix, "");
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.RenameAs") + " " + newLabel, "special.rename:" + this._name + "|,|" + newLabel, null, null, false, true, true);
			break;
		case "Contact":
			this._createBreak();
			
			var email = (this._email || this._name);
			if( email.indexOf("@")>-1 ) this._createLink(this.el, "Compose To " + email, "special.compose:" + email, null, null, false, true );
			
			this._createStatuses();
			this._createLabelsSection("Contexts", true);
			this._createLabelsSection("Projects", true);
			this._createLabelsSection("References", true);
			// Associated Contacts
			var rankedContacts = this._gtdinboxPage.sp.getRankedContactsByContact(email);
			if( rankedContacts.length > 0 ){
				var elContacts = this._doc.createElement("DIV");
				for( var i = 0; i < rankedContacts.length; i++ ){
					this._createLink( elContacts, rankedContacts[i], GIPROTOTYPE.restrictSearchToUser(rankedContacts[i], true), rankedContacts[i], "Contact", true);
				}
				this._createBreak();
				this._createSection((this._gtdinboxPage.stringBundle.getString("FilterPopup.Contacts")), elContacts);	
			}
			this._createBreak();
			this._createLink(this.el, this._gtdinboxPage.stringBundle.getString("FilterPopup.AssociatedFiles"), "has:attachment");	
			break;
	}
	
	// Search
	this._createBreak();
	var elSearch = this._doc.createElement("DIV");
		elSearch.className = "search";
	var elSearchInput = this._doc.createElement("INPUT");
		elSearchInput.setAttribute("type", "text");
	elSearch.appendChild( elSearchInput );
	var elSearchCmd = this._doc.createElement("BUTTON");
		elSearchCmd.innerHTML = this._gtdinboxPage.stringBundle.getString("FilterPopup.SearchButton");	
	elSearch.appendChild( elSearchCmd );
	this._createSection(this._gtdinboxPage.stringBundle.getString("FilterPopup.Search"), elSearch );	
	
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI create\n" + e.toString());
}
};
FilterPopupUI.prototype._hasParentType = function(type){
	for( var i = 0; i < this._parentTypes.length; i++ ){
		if( this._parentTypes[i]==type ){
			return true;
		}
	}
	return false;
};
FilterPopupUI.prototype._createBreak = function(elParent){
	if( !elParent ) elParent = this.el;
	
	var elBreak = this._doc.createElement("DIV");
		elBreak.className = "break";
	elBreak.innerHTML = "&nbsp;";
	
	elParent.appendChild( elBreak );
	
	return elBreak;
};
FilterPopupUI.prototype._createLink = function(elParent, title, search, name, type, canExpand, excludeParentSearch, cannotPopout){
try{	
	if( !excludeParentSearch ) search = this._parentSearch + " " + search;

	var elLink = this._doc.createElement("DIV");
		elLink.className = "link";
	if( elParent ) elParent.appendChild( elLink );
	
	var elBody = this._doc.createElement("DIV");
		elBody.className = "body";
		elBody.innerHTML = title;
	elLink.appendChild( elBody );
	
	var fAttribs = function(el){
		el.setAttribute("gtdSearch", search);
		if( name ) el.setAttribute("gtdName", name);
		if( type ) el.setAttribute("gtdType", type);
	};
	fAttribs(elLink);
	fAttribs(elBody);
	
	var elCmds = this._doc.createElement("DIV");
		elCmds.className = "commands";
	elLink.appendChild( elCmds );
	
	if( !cannotPopout ){
		var elPopout = this._doc.createElement("IMG");
			elPopout.className = "async-popuper";
			elPopout.src = "chrome://gtdinbox/skin/popout.png";
			elPopout.title = this._gtdinboxPage.stringBundle.getString("FilterPopup.tooltip.Open");	
			fAttribs(elPopout);
		elCmds.appendChild( elPopout );
	}
		
	if( name && canExpand ){
		var elExpander = this._doc.createElement("IMG");
			elExpander.className = "expander";
			elExpander.src = "chrome://gtdinbox/content/filter-extend.png";
			elExpander.title = this._gtdinboxPage.stringBundle.getString("FilterPopup.tooltip.Drill");	
		elCmds.appendChild( elExpander );
		fAttribs(elExpander);
	}
	
	var elClear = this._doc.createElement("DIV");
		elClear.style.clear = "both";
		elClear.style.height = "1px";
	elLink.appendChild( elClear );
	
	return elLink;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createLink\n" + e.toString());
}
};
FilterPopupUI.prototype._createSection = function(title, elContent, elParent){
try{
	elParent = elParent || this.el;
	var showHider = new Showhider(this._gtdinboxPage, "filter-" + title, {doc: this._doc, 'elParent':elParent, 'title':title, 'elContent': elContent});
	this._showHiders.push(showHider);
	return showHider;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createSection\n" + e.toString());
}
};
FilterPopupUI.prototype._createStatuses = function(){
try{
	this._createBreak();
	
	// Create set of links for statuses
	var labels = GIPROTOTYPE.clone(this._labels.getLabelsArray("Statuses"));
	
	var settings = this._gtdinboxPage.settings.labels.types.Statuses;
	var labelSearch = "";
	for( d in settings.defaults ){
		var label = settings.prefix + settings.defaults[d];

		for( var i = 0; i < labels.length; i++ ){
			if( labels[i]==label ){
				if( d=="Action" ){
					labelSearch = "(" + GIPROTOTYPE.searchableLabel(label) + " OR " + GIPROTOTYPE.searchableLabel(settings.prefix + settings.defaults.NextAction) + ")";
				}else{
					labelSearch = GIPROTOTYPE.searchableLabel(label);
				}
				this._createLink( this.el, label.replace(settings.prefix,""), labelSearch, label, "Statuses", true);
				labels.splice(i,1);
				i--;
			}
		}
	}
	// And the rest:
	for( var i = 0; i < labels.length; i++ ){
		var label = labels[i];
		this._createLink( this.el, label.replace(settings.prefix,""), GIPROTOTYPE.searchableLabel(label), label, "Statuses", true);
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createStatuses\n" + e.toString());
}
};
FilterPopupUI.prototype._createLabelsSection = function(type, isContact){
	// Get set of prioritised labels for this label; and all labels; then create box
try{
	this._createBreak();
	
	var settings = this._gtdinboxPage.settings.labels.types[type];
	var labelsHash = GIPROTOTYPE.clone(this._labels.getLabelsHash(type));
	
	var foundOne = false;
	// Grab related ones first:
	var related = null;
	if( isContact ){
		var related = this._sp.getRankedLabelsByContact(settings.prefix, (this._email || this._name) );
	}else{
		var related = this._sp.getRankedLabelsByLabel(settings.prefix, this._name);
	}
	var elRelated = this._doc.createElement("DIV");
	for( var i = 0; i < related.length; i++ ){
		var label = related[i];
		this._createLink( elRelated, label.replace(settings.prefix,""), GIPROTOTYPE.searchableLabel(label), label, type, true);
		if( labelsHash[label] ) delete labelsHash[label];
		foundOne = true;
	}
	// And process the rest
	var elMore = this._doc.createElement("DIV");
	for( label in labelsHash ){
		this._createLink( elMore, label.replace(settings.prefix,""), GIPROTOTYPE.searchableLabel(label), label, type, true);
		foundOne = true;
	}
	
	if( foundOne ){
		var showHider = this._createSection(this._gtdinboxPage.stringBundle.getString("FilterPopup.LabelsAll"), elMore, elRelated);
		this._createSection((this._gtdinboxPage.stringBundle.getString("FilterPopup." + type)||type), elRelated);			
		
		//if( related.length==0 ) showHider.show(true);	 // Annoying
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createLabelsSection\n" + e.toString());
}
};
FilterPopupUI.prototype._createContactsSectionByLabel = function(){
	// Find all contacts associated with this name
try{
	// Grab related ones first:
	var related = this._sp.getRankedContactsByLabel(this._name);
	if( related.length > 0 ){
		var elRelated = this._doc.createElement("DIV");
		for( var i = 0; i < related.length; i++ ){
			var contact = related[i];
			this._createLink( elRelated, contact, GIPROTOTYPE.restrictSearchToUser(contact, true), contact, "Contact", true);
		}
		this._createLink(elRelated, this._gtdinboxPage.stringBundle.getString("FilterPopup.Contacts.ComposeToAll"), "special.compose:" + related.join(", "), null, null, false, true);
		this._createSection(this._gtdinboxPage.stringBundle.getString("FilterPopup.Contacts"), elRelated);
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI createContactsSectionByLabel\n" + e.toString());
}
};

FilterPopupUI.prototype.contextMenu = function(event){
	var el = GIPROTOTYPE.element(event);
	if( el.getAttribute("gtdName") ){
		GIPROTOTYPE.stop(event);
		this.clickExtend(el);
	}
};
FilterPopupUI.prototype.mouseDown = function(event){
	
	try{
		var el = GIPROTOTYPE.element(event);
		if( event.button==2 ) return;
		if( event.shiftKey ){	// async
			this.forceOff();
			return;
		}
		
		// Detect the type (search button, extend button, regular filter)
		if( el.nodeName=="BUTTON" ){	// search
			el = el.parentNode.getElementsByTagName("INPUT")[0];
			this._gtdinboxPage.search( this._parentSearch + " " + el.value );
			GIPROTOTYPE.stop(event);
			this.forceOff();
		}else if( el.nodeName=="IMG" && el.getAttribute("gtdName") ){	// extend
			this.clickExtend(el);
			GIPROTOTYPE.stop(event);
		}else if( el.getAttribute("gtdSearch") ){
			var search = el.getAttribute("gtdSearch");
			if( search.indexOf("special.compose:")==0 ){
				this._gtdinboxPage._composeUI.clickComposeTo( search.replace("special.compose:", "") );
			}else if( search.indexOf("special.rename:")==0 ){
				var search = search.replace("special.rename:", "");
				var splitter = search.split("|,|");
				var rename = [splitter[0], splitter[1]];	// rename from and to
				var gtdinboxPage = this._gtdinboxPage;
				var finalCallback = GIPROTOTYPE.bind(this, function(){
					var el = gtdinboxPage.gmailDOM.element("inbox-link");
					GIPROTOTYPE.doMouseEvent(gtdinboxPage.doc, el, "click");	// refresh
				});
				this._gtdinboxPage.gmailDOM.renameLabel(rename, null, finalCallback);
			}else{
				this._gtdinboxPage.search( (search||"") );
			}
			GIPROTOTYPE.stop(event);
			this.forceOff();
		}
	}catch(e){
		if( GTDDEBUGMODE ) alert("filterpopup mouseDown\n" + e.toString());
	}
};
FilterPopupUI.prototype.clickExtend = function(el){
	// Use the line-item to generate new popup
try{
	if( this._filterChild ){	// turn off
		this._filterChild.destroy();
		this._filterChild = null;
		if( this._filterChildEl==el ) return;
	}
	var name = el.getAttribute("gtdName");
	var type = el.getAttribute("gtdType");
	var parentSearch = this._parentSearch + " " + (el.getAttribute("gtdSearch")||"");
	var parentTypes = this._parentTypes.concat( this._type );
	var parentNames = this._parentNames.concat( this._name );
	this._filterChild = new FilterPopupUI( this._gtdinboxPage, name, type, el, parentNames, parentTypes, parentSearch, this );
	this._filterChild.popup(el,{location:'right'});
	this._filterChildEl = el;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI clickExtend\n" + e.toString());
}
};

FilterPopupUI.prototype.addPopupChildObject = function(popupObj){
	// Add to this popuper as 'safe', and propogate up
	this._popuper.addPopupChild( popupObj );
	if( this._filterParent ) this._filterParent.addPopupChildObject( popupObj );
};

FilterPopupUI.prototype.highlighted = function(v){
	if( typeof v=="undefined" ) return GIPROTOTYPE.hasClassName(this.el, "filter-highlighted");
	if( v ){
		GIPROTOTYPE.addClassName(this.el, "filter-highlighted");
	}else{
		GIPROTOTYPE.removeClassName( this.el, "filter-highlighted");
	}
};

FilterPopupUI.prototype.forceOff = function(){
	// Find highest FilterPopupUI in chain; and destroy it
	var fp = this;
	while( fp._filterParent ) fp = fp._filterParent;
	fp.destroy();
};
FilterPopupUI.prototype.onPopupOff = function(){
	this.destroy();
};
FilterPopupUI.prototype.clickClose = function(){
	this.destroy();
}
FilterPopupUI.prototype.destroy = function(){
try{
	if( !this.el ) return;	// already destroyed
	
	if( this._filterParent ) this._filterParent.highlighted(true);
	
	if( this._filterChild ){	// turn off
		this._filterChild.destroy();
	}
	
	if( this.popupOff ) this.popupOff();
	if( this._popuper ) this._popuper.destroy();
	this._eventObservers.destroy();
	
	for( var i = 0; i < this._showHiders.length; i++ ){
		this._showHiders[i].destroy();
	}
	
	this._gtdinboxPage = null;
	this._doc = null;
	
	if( this.el && this.el.parentNode ) this.el.parentNode.removeChild(this.el);
	this.el = null;
}catch(e){
	if( GTDDEBUGMODE ) alert("FilterPopupUI destroy\n" + e.toString());
}
};










